#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
from models.word_code import numbers  #随机字符串
from models.email_code import email   #自动发送邮件
from models import chouti_db
from models import check_code
from models import is_number
import io
from datetime import datetime
from sqlalchemy import and_,or_
log_code=[]
class IdexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")



class HomeHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        self.render('home.html')


class SencodeHandler(tornado.web.RequestHandler):
    def post(self, *args, **kwargs):
        #获取 输入的邮箱
        email_to = self.get_argument('em',None).lower()
        # 发送验证码
        if email_to:
            #数据库游标，发送验证码前验证用户是否存在
            conne = chouti_db.session()
            ret_1 = conne.query(chouti_db.UserInfo).filter(chouti_db.UserInfo.username==email_to, chouti_db.UserInfo.status=="1").first()
            ret_2 = conne.query(chouti_db.UserInfo).filter(and_(chouti_db.UserInfo.username==email_to, chouti_db.UserInfo.status=="2")).first()

            if not ret_2:
                # 发送验证码
                code = numbers()
                email([email_to,], '请妥善保管 抽屉注册码:' + code)
                obj = chouti_db.UserInfo(username=email_to, code=code, stime=datetime.now(), status=1)
                if not ret_1:
                    conne.add(obj)
                else:
                    conne.query(chouti_db.UserInfo).filter(and_(chouti_db.UserInfo.username == email_to, chouti_db.UserInfo.status == "1")).update({"code":code,'stime':datetime.now()})
                conne.commit()
            else:
                self.write('*邮箱已注册*')
class RegisterHandler(tornado.web.RequestHandler):
    def post(self, *args, **kwargs):
        username= self.get_argument("em").lower()
        code = self.get_argument("cd").lower()
        pwd = self.get_argument("pwd").lower()
        is_num = is_number.is_null(username,code,pwd)
        conne = chouti_db.session()
        obj = chouti_db.UserInfo
        is_code = conne.query(obj).filter(obj.username == username, obj.code == code).first()  # 输入的验证码是否正确
        ret = conne.query(obj).filter(obj.username == username, obj.status == "2").first()
        ret_2 = conne.query(obj).filter(obj.username == username, obj.status == "1").first()  # 数据库是否存放了验证码

        if is_num =="1":

            if ret:
                self.write("用户已存在")
            else:
                if ret_2:
                    if is_code:
                        print(1)
                        obj_1 = obj(username=username, pwd=pwd,stime=datetime.now(), status=2)
                        conne.add(obj_1)
                        print(2)
                        conne.commit()
                        conne.query(obj).filter(obj.username == username, obj.status == "1").delete()  #添加完且commit 之后才能删除
                        conne.commit()
                        self.write("1")
                    else:
                        self.write("验证码超时或错误2")
                else:
                    self.write("验证码超时或错误1")

        else:
            self.write(is_num)


class CheckcodeHandler(tornado.web.RequestHandler):
    def get(self, *args, **kwargs):
        mstream = io.BytesIO()  # 容器
        img, code = check_code.create_validate_code()
        img.save(mstream, "GIF")
        if len(log_code)>0:
            log_code.pop(0)
        log_code.append(code)
        self.write(mstream.getvalue())




class LoginHandler(tornado.web.RequestHandler):
    def post(self, *args, **kwargs):
        username = self.get_argument("username").lower()
        code = self.get_argument("cd").lower()
        pwd = self.get_argument("pwd").lower()
        print(log_code)
        is_code = log_code[0].lower()

        conne = chouti_db.session()
        obj = chouti_db.UserInfo
        db_user= conne.query(obj).filter(obj.username == username, obj.pwd==pwd).first()
        if is_code==code:
            if db_user:
                self.write("1")
            else:
                self.write("帐号或者密码错误")
        else:
            self.write("验证码有误")











settings={
    "template_path":"views",
    "static_path":"statics",
    "static_url_prefix":"/ccc/",

}

application = tornado.web.Application([
    (r"/index", IdexHandler),
    (r"/sendcode", SencodeHandler),
    (r"/register", RegisterHandler),
    (r"/login", LoginHandler),

    (r"/check_code", CheckcodeHandler),
    (r"/home", HomeHandler),
],**settings)

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()